<template>
  <div>
    <!-- 搜速区 -->
    <div class="search">
      <label style="color: #666; font-size: 12px">角色：</label>
      <el-select
        size="mini"
        v-model="roleId"
        placeholder="请选择角色"
        clearable
        style="margin-right: 10px"
      >
        <el-option
          v-for="item in roleListToSearch"
          :key="item.roleId"
          :label="item.roleName"
          :value="item.roleId"
        >
        </el-option>
      </el-select>
      <el-button
        type="success"
        icon="el-icon-search"
        size="small"
        @click="searchClick"
      ></el-button>
      <el-button
        type="primary"
        icon="el-icon-document-add"
        size="small"
        @click="addClick"
      ></el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 99%" size="mini">
      <el-table-column label="编号" width="180">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="账号" width="180">
        <template slot-scope="scope">
          {{ scope.row.loginId }}
        </template>
      </el-table-column>
      <el-table-column label="昵称" width="180">
        <template slot-scope="scope">
          {{ scope.row.nickName }}
        </template>
      </el-table-column>
      <el-table-column label="电话" width="180">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="头像" width="180">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="
              BASE_URL_AdminImg +
              (scope.row.photo ? scope.row.photo : 'admin_default.png')
            "
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="180">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.role.roleName }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            @click="handleEdit(scope.$index, scope.row)"
            ><i class="el-icon-edit-outline"></i
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            ><i class="el-icon-delete"></i
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加抽屉 -->
    <el-drawer
      :title="isAdd ? '添加用户' : '修改用户'"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="drawerClose"
    >
      <div style="padding: 0 15px">
        <el-form
          size="mini"
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="75px"
          class="demo-ruleForm"
        >
          <el-form-item label="头像" prop="photo">
            <el-upload
              class="avatar-uploader"
              :action="UPLOAD_AdminImg_URL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="ruleForm.photo"
                :src="BASE_URL_AdminImg + ruleForm.photo"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="账号" prop="loginId">
            <el-input
              type="text"
              v-model="ruleForm.loginId"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="isAdd" label="密码" prop="loginPwd">
            <el-input
              type="password"
              v-model="ruleForm.loginPwd"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="isAdd" label="确认密码" prop="loginPwd2">
            <el-input
              type="password"
              v-model="ruleForm.loginPwd2"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              type="text"
              v-model="ruleForm.nickName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input
              type="text"
              v-model="ruleForm.phone"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select
              v-model="ruleForm.roleId"
              placeholder="请选择角色"
              clearable
            >
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">{{
              isAdd ? "添加" : "修改"
            }}</el-button>
            <el-button @click="resetForm('ruleForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <!-- 分页 -->
    <div class="flex j-c" style="margin-top: 10px">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="count"
        :page-size="6"
        hide-on-single-page
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
// 导入md5加密方法
import { strToMd5 } from "../../util/md5";
// 导入角色api
import * as role_api from "../../api/role_api";
// 导入用户头像根路径和上传路径
import { BASE_URL_AdminImg, UPLOAD_AdminImg_URL } from "../../config/index";
export default {
  data() {
    // 验证账号
    var validateLoginId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    var validateLoginPwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    var validateLoginPwd2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      } else if (value !== this.ruleForm.loginPwd) {
        callback(new Error("密码输入不一致"));
      } else {
        callback();
      }
    };
    var validateNickName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户昵称"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入电话"));
      } else {
        callback();
      }
    };
    var validateRoleId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选角色"));
      } else {
        callback();
      }
    };
    return {
      // 表格数据的总数量
      count: 0,
      // 角色编号(用于根据条件查询账号信息)
      roleId: "",
      // 当前页
      pageIndex: 1,
      // 表格数据
      tableData: [],
      // 角色选择列表
      roleList: [],
      // 角色列表(用于搜索)
      roleListToSearch: [],
      // 管理员头像根路径
      BASE_URL_AdminImg,
      // 管理员头像上传路径
      UPLOAD_AdminImg_URL,
      // 是否做添加操作
      isAdd: true,
      // 是否打开抽屉
      drawer: false,
      //表单数据
      ruleForm: {
        id: "",
        // 账号
        loginId: "",
        // 密码
        loginPwd: "",
        // 确认密码
        loginPwd2: "",
        // 昵称姓名
        nickName: "",
        // 电话
        phone: "",
        // 头像
        photo: "",
        // 角色ID
        roleId: "",
      },
      // 表单验证数据
      rules: {
        // 验证账号
        loginId: [{ validator: validateLoginId, trigger: "blur" }],
        loginPwd: [{ validator: validateLoginPwd, trigger: "blur" }],
        loginPwd2: [{ validator: validateLoginPwd2, trigger: "blur" }],
        nickName: [{ validator: validateNickName, trigger: "blur" }],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        roleId: [{ validator: validateRoleId, trigger: "change" }],
      },
    };
  },
  created() {
    // 调用获取表格数据的方法
    this.getTableData();
    this.getRoleList();
  },
  methods: {
    // 获取表格数据
    async getTableData() {
      let res = await this.$get("/admin/list", {
        roleId: this.roleId || 0,
        pageIndex: this.pageIndex,
        pageSize: 6,
      });
      this.tableData = res.data.list;
      this.count = res.data.total;
    },
    // 分页方法
    currentChange(pageIndex) {
      // 设置当前页码
      this.pageIndex = pageIndex;
      // 重新调用获取表格数据的方法
      this.getTableData();
    },
    async getRoleList() {
      let res = await this.$get("/role/list");
      this.roleList = res.data;
      this.roleListToSearch = res.data;
    },
    async handleEdit(index, row) {
      // 表示这是修改操作
      this.isAdd = false;
      // 打开抽屉
      this.drawer = true;

      let loginId = row.loginId;
      // 根据角色编号,获取角色对象
      let res = await this.$get("/admin/getOne", { loginId });
      this.ruleForm = res.data;
    },
    async handleDelete(index, row) {
      await this.$con_f("是否确定删除?");
      let id = row.id;
      let photo = row.photo;
      // 删除对应的角色信息
      let { success, message } = await this.$post("/admin/delete", {
        id,
        photo,
      });
      if (success) {
        this.$message({
          showClose: true,
          message: message,
          type: "success",
          duration: 1500,
        });
        // 获取最新数据
        this.getTableData();
      } else {
        this.$message({
          showClose: true,
          message: message,
          type: "error",
          duration: 1500,
        });
      }
    },
    // 添加按钮点击方法
    addClick() {
      this.drawer = true;
    },
    searchClick() {
      this.getTableData();
    },
    // 上传成功
    handleAvatarSuccess(res, file) {
      let { success, data, message } = res;
      if (success) {
        this.$message({
          showClose: true,
          message: message,
          type: "success",
          duration: 1500,
        });
        this.ruleForm.photo = data;
      }
    },
    // 上传之前
    beforeAvatarUpload(file) {
      // 定义可以上传的图片格式
      let imgTypeList = ["image/jpeg", "image/png", "image/gif"];
      const isType = imgTypeList.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 <= 2;

      if (!isType) {
        this.$message.error("上传头像图片只能是 JPG PNG GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isType && isLt2M;
    },
    // 关闭抽屉
    drawerClose(done) {
      // 清空表单数据
      this.resetForm("ruleForm");
      // 表单恢复成默认状态
      this.isAdd = true;
      done();
    },
    // 表单提交方法
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        // 判断表单数据是否验证成功
        if (valid) {
          if (this.isAdd) {
            // 对密码进行加密
            this.ruleForm.loginPwd = strToMd5(this.ruleForm.loginPwd);
            // 执行添加功能
            let { success, message } = await this.$post(
              "/admin/add",
              this.ruleForm
            );
            // 判断是否添加成功
            if (success) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              // 清空表单
              this.resetForm("ruleForm");
              // 关闭抽屉
              this.drawer = false;
              // 获取最新数据
              this.getTableData();
            } else {
              this.$message({
                showClose: true,
                message: message,
                type: "error",
                duration: 1500,
              });
            }
          } else {
            // 执行修改操作
            let { success, message } = await this.$get(
              "/admin/update",
              this.ruleForm
            );
            // 判断是否修改成功
            if (success) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              this.drawer = false;
              // 获取最新数据
              this.getTableData();
            } else {
              this.$message({
                showClose: true,
                message: message,
                type: "error",
                duration: 1500,
              });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 表单重置方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // 清空数据
      this.ruleForm = {
        // 账号
        loginId: "",
        // 密码
        loginPwd: "",
        // 确认密码
        loginPwd2: "",
        // 昵称姓名
        nickName: "",
        // 电话
        phone: "",
        // 头像
        photo: "",
        // 角色ID
        roleId: "",
      };
    },
  },
};
</script>
<style scoped lang='scss'>
.search {
  padding: 4px 10px;
}
.avatar-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  justify-content: space-around;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  max-width: 100%;
  max-height: 100%;
  display: block;
}
</style>